import { defineStore } from 'pinia'
import { ref } from 'vue'

import type { TaskSection } from '@/views/task/data'

export const useTaskStore = defineStore('task', () => {
  // 任务数据
  const taskSections = ref<TaskSection[]>([
    {
      title: '新人专享',
      tasks: [
        { id: 1, title: '收藏人人租机小程序', reward: 20, status: 'todo', icon: 'star-o' },
        { id: 2, title: '进行实名认证', reward: 30, status: 'todo', icon: 'user-o' },
      ],
    },
    {
      title: '每天逛逛',
      tasks: [
        { id: 3, title: '逛一逛活动页', reward: 10, status: 'todo', icon: 'search' },
        { id: 4, title: '逛一逛首页', reward: 10, status: 'todo', icon: 'search' },
        { id: 5, title: '逛一逛生活号首页', reward: 10, status: 'todo', icon: 'search' },
        { id: 6, title: '去分享', reward: 5, status: 'todo', icon: 'search' },
      ],
    },
  ])

  // 完成任务的方法
  const completeTask = (taskId: number): boolean => {
    for (const section of taskSections.value) {
      const task = section.tasks.find(t => t.id === taskId)
      if (task && task.status === 'todo') {
        task.status = 'completed'
        saveToLocalStorage()
        return true
      }
    }
    return false
  }

  // 重置所有任务
  const resetAllTasks = () => {
    for (const section of taskSections.value) {
      section.tasks.forEach(task => {
        task.status = 'todo'
      })
    }
    saveToLocalStorage()
  }

  // 保存到本地存储
  const saveToLocalStorage = () => {
    localStorage.setItem('taskSections', JSON.stringify(taskSections.value))
  }

  // 从本地存储加载
  const loadFromLocalStorage = () => {
    const savedTasks = localStorage.getItem('taskSections')
    if (savedTasks) {
      try {
        const parsedTasks = JSON.parse(savedTasks)
        if (Array.isArray(parsedTasks)) {
          taskSections.value = parsedTasks
        }
      } catch (error) {
        console.error('Failed to parse saved tasks:', error)
      }
    }
  }

  // 初始化时加载数据
  loadFromLocalStorage()

  return {
    taskSections,
    completeTask,
    resetAllTasks,
    loadFromLocalStorage
  }
}) 